#ifndef _READOUT_PCI_H
#define _READOUT_PCI_H

#include "pci22.h"

typedef struct {
  PCI_TYPE00 PCIData;
  UINT16     Bus;
  UINT16     Device;
  UINT16     Func;  
} PCITable;

#define CALC_EFI_PCI_ADDRESS(Bus,Dev,Func,Reg) \
  ( (UINT64) ( (((UINTN)Bus) << 24) + (((UINTN)Dev) << 16) + \
  (((UINTN)Func) << 8) + ((UINTN)Reg) ))

  

VOID
ReadoutPCI(
              UINT16     *DeviceCount,
		          PCITable   TableArray[]
              )
{
  UINT16 Bus;
  UINT16 Device;
  UINT16 Func;
  UINT16 DeviceNumber;
  UINT64 Address;
  EFI_STATUS  Status;

  EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL        *Protocol;
  
  
  DeviceNumber = 0;




  Status = BS->LocateProtocol(&gEfiPciRootBridgeIoProtocolGuid,
							   NULL,
							   &Protocol
							   );

  
  

  for (Bus = 0; Bus <= 255; Bus++) {  
    for (Device = 0; Device <= PCI_MAX_DEVICE; Device++) {	  
	    for (Func = 0; Func <= PCI_MAX_FUNC; Func++) {
		  
   	   Address = CALC_EFI_PCI_ADDRESS (
   									   Bus, 
   									   Device, 
   									   Func, 
   									   0
   									   );
   	 
   	   Protocol->Pci.Read (
   						  Protocol, 
   						  EfiPciWidthUint16, 
   						  Address, 
   						  24, 
   						  &TableArray[DeviceNumber]
   						  );
   
   	   	   
   	   //                       
   	   // Check VendorID == 0xFFFF 
   	   //
   	   if( TableArray[DeviceNumber].PCIData.Hdr.VendorId == 0xFFFF){
   		 continue;
   	   }   
   
   
         TableArray[DeviceNumber].Bus = Bus;
         TableArray[DeviceNumber].Device = Device;
         TableArray[DeviceNumber].Func   = Func;
         DeviceNumber++;	
         
	
	    
		   
		 }
	   }
	}  

	*DeviceCount = DeviceNumber;
	
};		   
		   
#endif